package com.wideplay.crosstalk.web;

import com.google.inject.Inject;
import com.wideplay.crosstalk.services.TweetManager;
import com.wideplay.crosstalk.tweets.Tweet;
import com.wideplay.warp.servlet.RequestScoped;
import com.wideplay.warp.widgets.At;
import com.wideplay.warp.widgets.Get;
import com.wideplay.warp.widgets.On;
import com.wideplay.warp.widgets.Post;

import java.util.List;

/**
 * This object models the home page and is responsible for rendering
 *  a user's tweets, and authoring new ones.
 *
 * @author Dhanji R. Prasanna (dhanji@gmail.com)
 */
@At("/home") @On("action") @RequestScoped
public class HomePage {
    //user context, tracks current user
    private User user;

    //page state variables
    private List<Tweet> tweets;
    private Tweet newTweet = new Tweet();

    //service dependencies
    private final TweetManager tweetManager;

    @Inject
    public HomePage(TweetManager tweetManager, User user) {
        this.tweetManager = tweetManager;
        this.user = user;
    }


    @Get("logout")
    public String logout() {
        user.logout();

        return "/login?message=Bye.";
    }

    
    @Get
    public String get() {

        //load tweets for current user
        this.tweets = tweetManager.tweetsFor(user.getUsername());


        //stay on current page
        return null;
    }


    @Post
    public String post() {
        newTweet.setAuthor(user.getUsername());

        //contents are in newTweet, add it to the data store
        tweetManager.addTweet(newTweet);

        //redirect back to this page using a GET
        return "/home";
    }


    //getters/setters...

    public String getUser() {
        return user.getUsername();
    }

    public List<Tweet> getTweets() {
        return tweets;
    }

    public Tweet getNewTweet() {
        return newTweet;
    }
}
